package com.solution.admin.customer.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.solution.admin.auth.constants.AuthConstants.IS_DELETE;
import com.solution.admin.auth.dao.UserDao;
import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.customer.constants.CustomerConstants;
import com.solution.admin.customer.dao.CompanyDao;
import com.solution.admin.customer.dao.CustomerDao;
import com.solution.admin.customer.dao.DeliveryModeDao;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.entity.DeliveryModeEntity;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.point.dao.PointDao;
import com.solution.admin.settings.dao.KeyMapDao;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.USER_APPROVE_STATUS;
import com.solution.common.constants.PublicStatus.USER_TYPE;
import com.solution.common.dao.BaseDao;
import com.solution.common.exception.BizException;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.service.impl.BaseServiceImpl;
import com.solution.common.utils.string.StringUtil;

/**
 * 客户信息service实现层
 * @author solin
 * @date 2017-09-22 11:35:12
 */
@Service
public class CustomerServiceImpl extends BaseServiceImpl<CustomerEntity> implements CustomerService {

	/**
	 * 客户信息接口
	 */
	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	private DeliveryModeDao deliveryModeDao;
	
	@Autowired
	private KeyMapDao keyMapDao;
	
	@Autowired
	PointDao pointDao;
	
	@Autowired
	UserDao userDao;
	
	@Autowired
	private CompanyDao companyDao;
	

	protected BaseDao<CustomerEntity> getDao() {
		return this.customerDao;
	}
	
	/**
	 * 更新用户
	 * @param customerEntity 用户实体
	 * @return Long 更新是否成功，>1代表更新成功
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@Transactional(rollbackFor=Exception.class)
	public int updateCustomer(CustomerEntity customerEntity) {
		int result = 0;
		//判断设置默认客户
		if (1 == customerEntity.getDefaultFlag()){
			CustomerEntity param = new CustomerEntity();
			param.setCompanyId(customerEntity.getCompanyId());
			param.setDefaultFlag(0);
			customerDao.updateByCompanyId(param);
		}
		
		result = customerDao.updateCustomer(customerEntity);
		
		if (result > 0) {
			//获取客户信息
			CustomerEntity customerInfo = customerDao.getById(customerEntity.getId());
			//如果是审核通过
			if (USER_APPROVE_STATUS.AGREE.getId().equals(customerEntity.getStatus())) {
				//同步到系统用户表
				customerInfo.setStatus(USER_APPROVE_STATUS.AGREE.getId());
				
				//将配件方式默认为全选
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("keyType", "deliveryMode");
				List<KeyMapEntity> keyList = keyMapDao.listKeyMap(param);
				List<DeliveryModeEntity> deliveryModeList = new ArrayList<DeliveryModeEntity>();
				for (int i = 0; i < keyList.size(); i++) {
					DeliveryModeEntity deliveryModeEntity = new DeliveryModeEntity();
					deliveryModeEntity.setCompanyId(customerInfo.getCompanyId());
					deliveryModeEntity.setModeValue(keyList.get(i).getKeyValue());
					deliveryModeEntity.setModeName(keyList.get(i).getKeyIntro());
					deliveryModeEntity.setCreater(customerInfo.getCreater());
					//以普通物流为默认物流
					if ("2".equals(keyList.get(i).getKeyValue())) {
						deliveryModeEntity.setDefaultFlag("1");
					}
					deliveryModeList.add(deliveryModeEntity);
				}
				deliveryModeDao.deleteDeliveryModeByCompanyId(customerInfo.getCompanyId());
				deliveryModeDao.batchSaveDeliveryMode(deliveryModeList);
			}
			syncToSysUserTable(customerInfo);
		}
		
		return result;
	}

	/**
	 * 保存客户信息
	 * 
	 * @param customerEntity
	 *            客户信息实体
	 * @return Long 添加成功客户信息的ID
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@Transactional(rollbackFor=Exception.class)
	public long saveCustomer(CustomerEntity customerEntity) {
		// 登录号即为手机号
		customerEntity.setLoginCode(customerEntity.getMobile());
		// 设置默认密码
		initDefaultPassword(customerEntity);
		// 设置默认客户
		if (customerEntity.getDefaultFlag() == 1) {
			CustomerEntity param = new CustomerEntity();
			param.setCompanyId(customerEntity.getCompanyId());
			param.setDefaultFlag(0);
			customerDao.updateByCompanyId(param);
		}
		// 检查状态是否为NULL
		if (null == customerEntity.getStatus()) {
			// 设置默认值，待审核
			customerEntity.setStatus(USER_APPROVE_STATUS.PENDING.getId()); 
		}
		// 设置默认性别
		if (0 == customerEntity.getGender()) {
			customerEntity.setGender(1);
		}
		// 设置删除状态为未删除
		customerEntity.setIsDelete(IS_DELETE.NOT_DELETE.getId()); 
		// 保存客户信息到客户信息表
		Long customerId = customerDao.saveCustomer(customerEntity);
		// 将新注册的客户信息同步到系统用户表sys_user; 同步信息中包含密码，有可能造成后续数据不一致
		if (customerId > 0 ) {
			syncToSysUserTable(customerEntity);
		}
		return customerId;
    }
	
	/**
	 * 设置初始密码
	 * @param customerEntity
	 */
	private void initDefaultPassword(CustomerEntity customerEntity){
		// 设置密码和加密盐
		String password = customerEntity.getPassword();
		if (StringUtil.isEmpty(password)) {
			password = "123456";
		}
		// 盐值
		Object salt = UUID.randomUUID();
		Object simpleHash = new SimpleHash("MD5", password, salt.toString(), 1);
		customerEntity.setPassword(String.valueOf(simpleHash));
		customerEntity.setPasswordSalt(String.valueOf(salt));
	}
	
	
	/**
	 * 分页查询客户信息
	 * @param pageParam 分页参数
	 * @param paramMap 查询参数
	 * @return PageBean 分页参数和分页数据
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@Override
	public PageBean listCustomerPage(PageParam pageParam, Map<String, Object> paramMap) {
		return customerDao.listCustomerPage(pageParam, paramMap);
	}
	
	/**
	 * 获取拥有微信OPEN_ID的用户
	 * @param param
	 * @return
	 * @author: solin
	 * @date: 2017年12月4日 下午1:40:41
	 */
	@Override
	public PageBean listWechatCustomerPage(PageParam pageParam, Map<String, Object> paramMap) {
		return customerDao.listWechatCustomerPage(pageParam, paramMap);
	}
	
	/**
	 * 根据ID查询用户信息
	 * @param id 用户id
	 * @return customerEntity 用户对象
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	public CustomerEntity getCustomerById(Long id) {
		return customerDao.getById(id.longValue());
	}

	/**
	 * 根据条件查询客户信息
	 * @param param
	 * @return 数据列表
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@Override
	public List<CustomerEntity> listCustomer( Map<String, Object> param){
		return  customerDao.listCustomer(param);
	}
	
	/**
	 * 删除客户信息
	 * @param 
	 * @return int 返回删除记录条数
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	public int deleteCustomerById(long id){
		return  customerDao.deleteById(id);
	}
	
	/**
	 * 判断客户账号唯一性
	 * @param userCodeOrMobileOrOpenId
	 * @return
	 * @author: solin
	 * @date: 2017年11月22日 上午10:20:29
	 */
	@Override
	public List<CustomerEntity> checkCustomerUnique(String userCodeOrMobileOrOpenId) {
		return customerDao.checkCustomerUnique(userCodeOrMobileOrOpenId);
	}
	
	/**
	 * 变更密码
	 * @param customerId
	 * @param password 如果密码传入为空，则设置为默认密码
	 * @return
	 * @author: solin
	 * @date: 2017年11月24日 上午10:18:29
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public int updateCustomerPassword(String mobile, String password) {
		CustomerEntity customerInfo =customerDao.getCustomerByCode(mobile);
		CustomerEntity customerEntity = new CustomerEntity();
		//设置密码和加密盐
		if (StringUtil.isEmpty(password)) {
			password = "123456";
		}
		//盐值
		Object salt = customerInfo.getPasswordSalt();
		Object simpleHash = new SimpleHash("MD5", password, salt.toString(), 1);
		customerEntity.setPassword(String.valueOf(simpleHash));
		customerEntity.setMobile(mobile);
		customerEntity.setId(customerInfo.getId());
		int res = customerDao.updatePassword(customerEntity);
		
		if (res > 0) {
			UserEntity userEntity = new UserEntity();
			// 用户编号/手机号
			userEntity.setMobile(mobile);
			// 用户密码
			userEntity.setPassword(customerEntity.getPassword());
			userDao.updateUserPwdByMobile(userEntity);
		}
		
		return res;
	}
	
	
	/**
	 * 查询合同上显示的客户代表信息
	 * @return
	 * @author lilp
	 */
	@Override
	public CustomerEntity  listContractCustomer(Map<String, Object> param){
		return customerDao.listContractCustomer(param);
	}
	
	/**
	 * 统计待审核人员数
	 * @return
	 * @author: solin
	 * @date: 2017年12月26日 下午7:47:59
	 */
	@Override
	public Integer countPengdingApproval() {
		return customerDao.countPengdingApproval();
	}
	
	/**
	 * 业务员获取我的客户数 
	 * @param salesmanId
	 * @return
	 * @author: solin
	 * @date: 2018年1月1日 下午4:13:20
	 */
	@Override
	public Integer getMyCustomerCount(String salesmanId) {
		return customerDao.getMyCustomerCount(salesmanId);
	}
	
	/**
	 * 获取所有已审核客户数
	 * @return
	 * @author: solin
	 * @date: 2018年1月7日 下午11:02:47
	 */
	@Override
	public Integer countAuditedCustomers() {
		return customerDao.countAuditedCustomers();
	}
	
	/**
	 * 获取新增客户数
	 * @return
	 * @author: solin
	 * @date: 2018年1月7日 下午11:02:47
	 */
	@Override
	public Integer countNewCustomers(Integer days) {
		return customerDao.countNewCustomers(days);
	}
	
	/**
	 * 同步到系统用户表
	 * @param customerEntity
	 * @return
	 * @author: solin
	 * @date: 2017年12月28日 下午7:47:10
	 */
	private int syncToSysUserTable(CustomerEntity customerEntity){
		UserEntity userEntity = new UserEntity();
		
		//判断系统user是否已存在
		UserEntity userInfo = userDao.getUserByCode(customerEntity.getLoginCode());

		// 用户编号/手机号
		userEntity.setUserCode(customerEntity.getLoginCode());
		// 用户名称
		userEntity.setUserName(customerEntity.getUserName());
		// 用户性别
		userEntity.setUserGender(String.valueOf(customerEntity.getGender()));
		// 用户密码
		userEntity.setPassword(customerEntity.getPassword());
		// 盐值
		userEntity.setPasswordSalt(customerEntity.getPasswordSalt());
		// 手机
		userEntity.setMobile(customerEntity.getMobile());
		// 邮箱
		userEntity.setEmail(customerEntity.getEmail());
		// 微信 OpenId
		userEntity.setOpenId(customerEntity.getOpenId());
		// 状态(用户正常状态)
		userEntity.setStatus(1);
		
		if (null == userInfo) {
			// 经销商ID
			userEntity.setDealerId(1L);
			// 删除标记
			userEntity.setIsDelete(1);
			// 用户类型
			userEntity.setUserType(USER_TYPE.CUSTOMER.getId()); // 设置用户类型为4（客户）
			// 创建人
			userEntity.setCreater(customerEntity.getCreater());
			// 添加时间
			userEntity.setCreateTime(new Date());
			
			return (int)userDao.saveUser(userEntity);
		} else {
			userEntity.setId(userInfo.getId());
			// 修改人
			userEntity.setModifier(customerEntity.getCreater());
			// 修改时间
			userEntity.setModifyTime(new Date());
			
			return userDao.update(userEntity);
		}
		
	}

	/**
	 * PC端用户注册逻辑
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
	public int registUserFromPc(CustomerEntity customer, CompanyEntity company) {
		int result;
		try {
			// 公司信息赋值
			customer.setLoginCode(customer.getMobile());
			company.setStatus(STATUS.ENABLED.getId());
			company.setCreater(customer.getLoginCode());
			// 如果公司名称为空
			if (StringUtil.isEmpty(company.getCompanyName())) {
				company.setCompanyName(customer.getUserName().concat("(").concat(customer.getMobile()).concat(")"));
			}
			// 设置默认业务员 和 默认客户系数
			company.setCustomerFactor(CustomerConstants.DEFAULT_CUTOMER_FACTOR);
			// 设置默认的业务员
			// 查询默认业务员工作号
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("keyType", "defaultSalesmanCode");
			List<KeyMapEntity> defaultSalesmanList = keyMapDao.listKeyMap(param);
			company.setSalesmanCode(defaultSalesmanList.get(0).getKeyValue());
			company.setIsDelete(PublicStatus.IS_DELETE.NORMAL.getId());

			// 保存公司信息
			Long companyId = companyDao.saveCompany(company);
			// 保存客户信息
			customer.setCompanyId(companyId);
			// 客户性别默认为男性
			customer.setGender(1); 
			// 设置为默认联系人
			customer.setDefaultFlag(1); 
			// 待审核
			customer.setStatus(USER_APPROVE_STATUS.PENDING.getId());
			// 创建人
			customer.setCreater(customer.getLoginCode());
			// 设置默认密码
			initDefaultPassword(customer);
			Long customerId = customerDao.saveCustomer(customer);
			
			// 将新注册的客户信息同步到系统用户表sys_user; 同步信息中包含密码，有可能造成后续数据不一致
			if (customerId > 0 ) {
				syncToSysUserTable(customer);
			}
			// 生成客户自己的邀请码(限定5位)
			String invitationCode = new DecimalFormat("00000").format(customerId);
			CustomerEntity updateCustomerEntity = new CustomerEntity();
			updateCustomerEntity.setId(customerId);
			updateCustomerEntity.setInvitationCode(invitationCode);
			result = customerDao.updateCustomer(updateCustomerEntity);
			
		} catch (Exception e) {
			// 抛出异常回滚事务
			throw new BizException("PC端用户注册失败", e);
		}
		return result;
	}
	
	/**
	 * 我的客户-区域列表
	 * 
	 * @param param
	 * @return List<Map<String,String>>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年5月17日 下午10:51:37
	 */
	public List<Map<String, String>> listOfAreaCombo(Map<String, Object> param) {
		return customerDao.listOfAreaCombo(param);
	}

	/**
	 * 我的客户分页查询
	 * 
	 * @param pageParam
	 * @param param
	 * @return PageBean
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年5月17日 下午10:51:26
	 */
	public PageBean listOfMyCustomerPage(PageParam pageParam, Map<String, Object> param) {
		return customerDao.listOfMyCustomerPage(pageParam, param);
	}

	/**
	 * 根据邀请码获取用户
	 * @param invitationCode
	 * @return
	 * @author xkl
	 * @date 2018年6月26日 下午7:07:01
	 */
	@Override
	public CustomerEntity getCustomerByInviationCode(String invitationCode) {
		return customerDao.getCustomerByInviationCode(invitationCode);
	}
	
	/**
	 * 分页查询客户信息
	 * @param pageParam
	 * @param paramMap
	 * @return
	 */
	public PageBean listCustomerPageForSelector(PageParam pageParam, Map<String, Object> paramMap){
		return customerDao.listCustomerPageForSelector(pageParam , paramMap);
	}
}
